(function () {
	angular.module('app.mainPage', ['mgcrea.ngStrap'])
	.controller('mainPageCtrl',function($scope,$rootScope,$tab){
		$scope.appInfos=apps;
		$scope.subjects=subjects;
		angular.forEach(subjects,function(item){
			if(item.selected){
				$scope.selectedSubject=item;
			}
		});
		
		//是否存在快捷菜单
		$scope.existsQuick=false;
		angular.forEach($scope.appInfos,function(app){
			angular.forEach(app.items,function(item){
				if(item.workBench==1){
					$scope.existsQuick=true;
				}
			});
		});
		
		$scope.tabs = [];
		$scope.tabs.activeTab = 0;
		//APP_ITEM中配置的TAB页
		$scope.pushTab=function(activeItem){
			 console.log(activeItem);
			 var index=-1;
			 var exists=false;
			 angular.forEach($scope.tabs,function(item){
				 if(!exists){
					 index++;
				 }
				 if(activeItem.itemID==item.itemID){
					 exists=true;
				 }
			 });
			 if(!exists){
				 activeItem.itemName=activeItem.itemName;
				 $scope.tabs.push(activeItem);
				 index++;
				 setTimeout(function(){$('#'+activeItem.appID+activeItem.itemID+"Tab").tab('show');},100);
			 }
			 $scope.tabs.activeTab= index;
			 $('#'+activeItem.appID+activeItem.itemID+"Tab").tab('show');
		 }
		
		//APP_INFO中配置的Tab页
		$scope.pushAppTab=function(app){
			if(!app.url){
				return;
			}
			var item={};
			item.appID=app.appID;
			item.itemID="_"+app.appID;
			item.itemName=app.appName;
			item.url=app.url;
			$scope.pushTab(item);
		}
		//移除Tab页
		$scope.removeTab=function(itemId){
			var index=-1;
			 var exists=false;
			angular.forEach($scope.tabs,function(item){
				if(!exists){
					 index++;
				 }
				 if(itemId==item.itemID){
					 exists=true;
				 }
			 });
			if(exists){
				$scope.tabs.splice(index,1);
			}
			$('#dashboardTab').tab('show');
		}
	}).directive('appItems', ['$http', '$templateCache', '$compile', function($http, $templateCache, $compile) {
		 return {
             restrict: 'A',
             link: function (scope, element, attrs) {
            	 var tpl = $templateCache.get('itemTpl');
            	 var pScope = scope.$new();
            	 pScope.items=scope.appInfos[attrs.appIndex].items;
            	var comEle = $compile(tpl)(pScope);
            	element.after(comEle);
             }
         }
	}]).directive('quickAppItems', ['$http', '$templateCache', '$compile', function($http, $templateCache, $compile) {
		 return {
             restrict: 'A',
             link: function (scope, element, attrs) {
            	 var tpl = $templateCache.get('quickItemTpl');
            	 var pScope = scope.$new();
            	 pScope.items=scope.appInfos[attrs.appIndex].items;
            	var comEle = $compile(tpl)(pScope);
            	element.after(comEle);
             }
         }
	}]);
})();